package cn.rtplay.esp32camcar.SteeringWheelSeekBar;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

/**
 * 自定义SeekBar 前景部分
 */
public class SeekBarForegroundView extends View {
    private Paint paint;
    private final int foregroundSize;
    private final int foreground;
    private Bitmap bitmapPaint;
    private Rect src;
    private Rect dst;
    // Matrix类进行图片处理（缩小或者旋转）
    private final Matrix matrix = new Matrix();
    private float deg;


    public SeekBarForegroundView(Context context, int foregroundSize, int foreground) {
        super(context);
        this.foregroundSize = foregroundSize;
        this.foreground = foreground;
        init();
    }

    public SeekBarForegroundView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.foregroundSize = 10;
        this.foreground = 0;
        init();
    }

    private void init() {
        paint = new Paint();
        //设置抗锯齿,防止过多的失真
        paint.setAntiAlias(true);
        if (foreground != 0) {
            bitmapPaint = BitmapFactory.decodeResource(this.getResources(), foreground);
            // 指定图片绘制区域(原图大小)
            src = new Rect(0, 0, bitmapPaint.getWidth(), bitmapPaint.getHeight());
            // 指定图片在屏幕上显示的区域(ballSize大小)
            dst = new Rect(0, 0, foregroundSize, foregroundSize);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int spec = View.MeasureSpec.makeMeasureSpec(foregroundSize, View.MeasureSpec.EXACTLY);
        setMeasuredDimension(spec, spec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (foreground == 0) {
            canvas.drawCircle((float) getMeasuredWidth() / 2, (float) getMeasuredWidth() / 2, (float) getMeasuredWidth() / 2, paint);
        } else {
            // 旋转
            matrix.setRotate(deg % 360, (float) foregroundSize / 2, (float) foregroundSize / 2);
            canvas.setMatrix(matrix);
            canvas.drawBitmap(bitmapPaint, src, dst, paint);
        }
    }


    /**
     * @param degrees 旋转角度
     */
    public void setDegrees(float degrees) {
        deg = degrees;
        postInvalidate();
    }
}